﻿using System;
using System.Collections.Generic;
using System.Linq;
using AMM.CustomClassLibrary;
using AMM.DataAccess.Store;
using AMM.Model;
using AMM.Model.Store;

namespace AMM.Business.Store {
    public class StoreBasisProcessor : BaseProcessor {

        private StoreBasisRepository _storeBasisRepository;

        public StoreBasisProcessor() {
            this._storeBasisRepository = new StoreBasisRepository();
        }

        public StoreBasi FetchStoreBasisById(int storeBasisId) {
            try {
                return this._storeBasisRepository.FetchStoreBasisById(storeBasisId);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("获取指定仓库基本资料数据失败！");
            }
        }

        public List<StoreBasisViewModel> FetchStoreBasis() {
            try {
                return this._storeBasisRepository.FetchStoreBasis().Select(x => {
                    return new StoreBasisViewModel() {
                        Key = x.StoreBasisId,
                        Code = x.Code,
                        Name = x.Name,
                        Description = x.Description,
                        IsEnabled = x.IsEnabled,
                        StoreType = x.Basic.Name,
                        AreaRemarks = x.AreaRemarks,
                        CreatedBy = x.CreatedBy,
                        CreatedDatetime = x.CreatedDatetime,
                        ModifiedBy = x.ModifiedBy,
                        ModifiedDatetime = x.ModifiedDatetime
                    };
                }).ToList();
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("获取仓库基本资料列表失败！");
            }
        }

        public List<StoreBasi> FetchEnabledStoreBasis() {
            List<StoreBasi> resultList = this._storeBasisRepository.FetchStoreBasis().Where(x => x.IsEnabled).ToList();
            resultList.Insert(0, new StoreBasi());
            return resultList;
        }

        public void Insert(StoreBasi storeBasis) {
            try {
                storeBasis.StoreBasisId = Guid.NewGuid().GetHashCode();
                storeBasis.CreatedDatetime = DateTime.Now;
                this._storeBasisRepository.Insert(storeBasis);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("插入新仓库基本资料失败！");
            }
        }

        public void Update(StoreBasi storeBasis) {
            try {
                storeBasis.ModifiedDatetime = DateTime.Now;
                this._storeBasisRepository.Update(storeBasis);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("更新仓库基本资料失败！");
            }
        }
    }
}
